package com.myrock.zlbandy.gorock.rock.ui;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.etsy.android.grid.StaggeredGridView;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;

import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.myrock.zlbandy.gorock.HttpModel.ParseInfo;
import com.myrock.zlbandy.gorock.HttpModel.Model.RockInfo;
import com.myrock.zlbandy.gorock.rock.tools.TakePhotoUtils;

import com.myrock.zlbandy.gorock.my.adapter.MyGridViewAdapter;
import com.myrock.zlbandy.gorock.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class ClassifyActivity extends BaseActivity implements AbsListView.OnScrollListener,AbsListView.OnItemClickListener{

    private Button media,photo;
    private static final int TAKE_PHOTO_REQUEST_TWO = 444;
    private static final int TAKE_PHOTO_REQUEST_ONE = 333;
    private static final int TAKE_PHOTO_REQUEST_THREE = 555;

//    private ImageView iv_image;
    private Uri imageUri;
    private TextView title;
    private ContentResolver resolver = null;
    private byte[] mContent;
    private ProgressBar myProgressBar;
    private TextView textView;
    private StaggeredGridView gridView;
    private BarData data;
    private BarDataSet dataSet;
    XAxis xAxis;
    private ArrayList<RockInfo> rockInfos = new ArrayList<RockInfo>();


    protected HorizontalBarChart mChart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify);
        media = (Button)findViewById(R.id.media);
        title = (TextView)findViewById(R.id.title);
        title.setTextSize(20);
        textView = (TextView) findViewById(R.id.tv);
        myProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mChart = (HorizontalBarChart) findViewById(R.id.chart1);
        mChart.setTouchEnabled(false);

        //x坐标轴设置
        xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴标签显示位置
        xAxis.setDrawGridLines(false);//不绘制格网线
        xAxis.setGranularity(1f);//设置最小间隔，防止当放大时，出现重复标签。
        xAxis.setLabelCount(12);//设置x轴显示的标签个数
        xAxis.setAxisLineWidth(2f);//设置x轴宽度, ...其他样式

//y轴设置
        YAxis leftAxis = mChart.getAxisLeft();//取得左侧y轴
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);//y轴标签绘制的位置
        leftAxis.setDrawGridLines(true);//不绘制y轴格网线
        leftAxis.setDrawLabels(true);//不显示坐标轴上的值, ...其他样式


        leftAxis.setAxisMaximum(100);
        leftAxis.setAxisMinimum(0);
        mChart.getAxisRight().setEnabled(false);


        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setFormSize(8f);
        l.setXEntrySpace(4f);
        l.setEnabled(false);

        gridView = (StaggeredGridView) this.findViewById(R.id.grid_view);
        gridView.setOnItemClickListener(this);

        mChart.setVisibility(View.INVISIBLE);

        media.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    imageUri = TakePhotoUtils.takePhoto(ClassifyActivity.this, TAKE_PHOTO_REQUEST_THREE);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        photo = (Button)findViewById(R.id.file);
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickImageFromAlbum();
            }
        });
//        iv_image = (ImageView) findViewById(R.id.iv_image);

    }

    public void pickImageFromAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, 111);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 111:
            case 222:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(ClassifyActivity.this, "点击取消从相册选择", Toast.LENGTH_LONG).show();
                    return;
                }

                try {
                    Uri imageUri = data.getData();
                    Log.e("TAG", imageUri.toString());
                    Bitmap bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
//                    iv_image.setImageBitmap(bitmap2);
                    classifyPhoto(bitmap2);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case TAKE_PHOTO_REQUEST_ONE:
                if (resultCode == RESULT_CANCELED) {
                    delteImageUri(ClassifyActivity.this, imageUri);
                    Toast.makeText(ClassifyActivity.this, "点击取消  拍照", Toast.LENGTH_LONG).show();
                    return;
                }

                try {

                    //如果拍照图片过大会无法显示
                    Bitmap bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
//                    iv_image.setImageBitmap(bitmap1);
                    classifyPhoto(bitmap1);


                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case TAKE_PHOTO_REQUEST_TWO:
                if (resultCode == RESULT_CANCELED) {
                    delteImageUri(ClassifyActivity.this, imageUri);
                    return;
                }
                Bitmap photo = data.getParcelableExtra("data");
//                iv_image.setImageBitmap(photo);
                classifyPhoto(photo);


                break;
            case TAKE_PHOTO_REQUEST_THREE:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(ClassifyActivity.this, "点击取消从相册选择", Toast.LENGTH_LONG).show();
                    return;
                }

                Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath(), getOptions(imageUri.getPath()));
//                iv_image.setImageBitmap(bitmap);
                classifyPhoto(bitmap);

                break;
            default:
                break;

        }

    }

    private void classifyPhoto(Bitmap bitmap){
        rockInfos.clear();
        myProgressBar.setVisibility(View.VISIBLE);
        mChart.setVisibility(View.INVISIBLE);
        MyGridViewAdapter adapter = new MyGridViewAdapter(ClassifyActivity.this, R.layout.activity_custom_grid_view,
                rockInfos, new int[]{R.id.imageView1});
        gridView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        ClassifyTask classifyTask = new ClassifyTask(myProgressBar,textView,getApplicationContext());
        classifyTask.execute(encode(bitmap));
    }


    private String encode(Bitmap bitmap) {
        //decode to bitmap

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();

        //base64 encode
        return  Base64.encodeToString(bytes,Base64.DEFAULT);
    }

    public static void delteImageUri(Context context, Uri uri) {
        context.getContentResolver().delete(uri, null, null);

    }


    /**
     * 获取压缩图片的options
     *
     * @return
     */
    public static BitmapFactory.Options getOptions(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inSampleSize = 4;      //此项参数可以根据需求进行计算
        options.inJustDecodeBounds = false;

        return options;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent  = new Intent(ClassifyActivity.this,RockInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("rockInfo",rockInfos.get(position));
        intent.putExtras(bundle);
        startActivity(intent);

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    class ClassifyTask extends AsyncTask<String, Integer, ArrayList<RockInfo>> {

        ProgressBar myprogressbar = null;
        //MainActivity的文本
        TextView textView = null;
        // MainActivity的上下文
        Context mycontext = null;
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        public ClassifyTask(ProgressBar progressbar, TextView textview, Context context) {
            myprogressbar = progressbar;
            mycontext = context;
            textView = textview;
        }
        @Override
        protected void onPreExecute() {
            textView.setVisibility(View.VISIBLE);
           // myProgressBar.setVisibility(View.VISIBLE);
            textView.setText("正在识别...");
            myprogressbar.setProgress(10);

        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected ArrayList<RockInfo> doInBackground(String... params) {
            ArrayList<RockInfo> arrayList = new ArrayList<RockInfo>();
            arrayList = ParseInfo.ClassifyPhoto(params[0]);
            for(int i = 50;i<99;i++){
                publishProgress(i);
            }
            return arrayList;


        }



        //onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            int progress = myprogressbar.getMax() / 100 * (progresses[0] + 1);
            myprogressbar.setProgress(progress);
            textView.setText("正在识别..." + progress + "%");
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(ArrayList<RockInfo> result) {
            mChart.setVisibility(View.VISIBLE);
            myprogressbar.setVisibility(View.GONE);
            textView.setVisibility(View.GONE);
            rockInfos.clear();
            rockInfos = result;
            if(result.size()>0) {
                ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();
                ArrayList<String> xVals = new ArrayList<String>();
                DecimalFormat df = new DecimalFormat("#.##");
                int j = 0;
                for (int i = result.size(); i >0; i--) {
                  float y = Float.parseFloat(df.format(result.get(i-1).getProbability()*100));
                    yVals.add(new BarEntry(j++,y));
                    xVals.add(result.get(i-1).getChinese());
                }
                dataSet=new BarDataSet(yVals,"识别精度");
                dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
                data = new BarData(dataSet);
                xAxis.setValueFormatter(new IndexAxisValueFormatter(xVals));
                Description description = new Description();
                description.setText("识别精度百分比");
                mChart.setDescription(description);
                mChart.setData(data);
                mChart.animateY(3000);

                MyGridViewAdapter adapter = new MyGridViewAdapter(ClassifyActivity.this, R.layout.activity_custom_grid_view,
                        rockInfos, new int[]{R.id.imageView1});
                gridView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
            else{
                Toast.makeText(getApplicationContext(),"oh,我受不了",Toast.LENGTH_SHORT).show();
            }

        }

        //onCancelled方法用于在取消执行中的任务时更改UI
        @Override
        protected void onCancelled() {

        }
    }
}

